package com.practise.websrc;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;

import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Mono;

import java.net.URI;


@SpringBootApplication
@Slf4j
public class WebSrcExample implements ApplicationRunner {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private WebClient webClient;

    public static void main(String[] args) {
        new SpringApplicationBuilder()
                .sources(WebSrcExample.class)
                .bannerMode(Banner.Mode.OFF)
                .web(WebApplicationType.NONE)
                .run(args);
    }

    @Bean
    public RestTemplate getRestTemplate(RestTemplateBuilder builder){
        return builder.build();
    }

    @Bean
    public WebClient getwebClient(){
        return WebClient.create();
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //1. 通过restTemplate获取web资源
        URI uri = UriComponentsBuilder
                .fromUriString("http://localhost:8081/practise/hello")
                .build(1);
        ResponseEntity<Object> resp = restTemplate.getForEntity(uri,Object.class);
        log.info("response is :{}",resp.getBody().toString());

        // 2. 通过webClient获取web资源
        Mono<String> mono= webClient.get()
                .uri("http://localhost:8081/practise/getuser")
//                .accept(MediaType.APPLICATION_XML)
                .retrieve()
                .bodyToMono(String.class)
                ;

        log.info("webclient response {}",mono.block());
    }
}
